package com.xiaoran.service.zk;

import com.xiaoran.service.config.ServerValue;
import com.xiaoran.common.annotation.RpcClient;
import com.xiaoran.common.annotation.RpcService;
import com.xiaoran.common.utils.IpUtil;
import com.xiaoran.common.utils.SpringBeanFactory;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class ServicePushManager {
    
    @Autowired
    private ZKit zKit;
    
    @Autowired
    private ServerValue serverValue;

    /**
     * 注册到zk
     */
    public void registerIntoZK() {
        //扫描所有标识RpcServer 注解的类
        Map<String, Object> beanListByAnnotationClass = SpringBeanFactory.getBeanListByAnnotationClass(RpcClient.class);
        if (MapUtils.isEmpty(beanListByAnnotationClass)){
            return;
        }
        //将接口信息注册到zk
        zKit.createRootNode();
        
        for (Object bean : beanListByAnnotationClass.values()) {
            RpcService annotation = bean.getClass().getAnnotation(RpcService.class);
            String serviceName = annotation.cls().getName();
            pushServiceInfoIntoZK(serviceName);
        }
    }

    private void pushServiceInfoIntoZK(String serviceName) {
        zKit.createPersistentNode(serviceName);
        
        String serviceAddress= IpUtil.getHostAddress()
                +":"+ serverValue.getServerPort()
                +":"+ serverValue.getNetworkPort();
        String serviceAddressPath = serviceName + "/" + serviceAddress;
        zKit.createNode(serviceAddressPath);
    }
}
